<?php
/**
 * 附件部分
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-05-05
 * @author monkee
 */

class attachmentModel extends model
{
	function create($forum_id, $user_id, $file_size, $file_name, $file_path){
		$file_type = $this->get_type_by_file_name($file_name);
		$arr = array(
			'relate_id' => $forum_id,
			'user_id' => $user_id,
			'file_name' => $file_name,
			'file_size' => $file_size,
			'file_type' => $file_type,
			'file_path' => $file_path,
			'mktime' => TIMESTAMP
		);
		DB::columnAdd('forum', 'atta_count', 'forum_id = '.$forum_id, 1);
		$arr['attachment_id'] = DB::insert('attachment', $arr);
	}
	function get_type_by_file_name($file_name){
		$start = strrpos($file_name, '.');
		if($start !== FALSE){
			return substr($file_name, $start);
		}
		return 'unknown';
	}
	function save_file(&$data, $file_name){
		$type = $this->get_type_by_file_name($file_name);
		$local_name = md5(microtime()).$type;
		$dir = 'cache/attachment/'.$local_name;
		if(file_put_contents(ROOT.$dir, $data)){
			$data = '';
			unset($data);
			return '/'.$dir;
		}else{
			return '';
		}
	}
	
	public function get_attachments_by_forum_id($forum_id){
		return DB::fetchArray('SELECT a.*, b.username FROM '.DB::table('attachment')." a LEFT JOIN ".DB::table('user')." b ON a.user_id = b.user_id WHERE relate_id = {$forum_id}");
	}
	
	public function get_attachment($attachment_id){
		return DB::fetchOne('SELECT * FROM '.DB::table('attachment')." WHERE attachment_id = {$attachment_id}");
	}
}
?>